import 'package:flutter/material.dart';
import 'package:macnov/models/transaction.dart';
import 'package:macnov/utils/Api.dart';
import 'package:macnov/utils/dateutil.dart';
import 'package:mobx/mobx.dart';

// Include generated file
part 'transaction.g.dart';

// This is the class used by rest of your codebase
class TransactionStore = _TransactionStore with _$TransactionStore;

int dateCompare(TransactionModel a, TransactionModel b) {
  return DateTime.parse(a.date).millisecondsSinceEpoch -
      DateTime.parse(b.date).millisecondsSinceEpoch;
}

// The store-class
abstract class _TransactionStore extends ChangeNotifier with Store {
  @observable
  List txns = [];

  @observable
  List filterTxns = [];

  @observable
  bool loading = false;

  @observable
  List budgetTxns = [];

  @action
  Future loadTxn() async {
    var txnsData = await Api.loadTxn();
    if (txnsData != null) {
      txns = txnsData.map((txn) => TransactionModel.fromJson(txn)).toList();
      txns.sort((a, b) => DateUtil.ddmmyyyyParse((b as TransactionModel).date)
          .compareTo(DateUtil.ddmmyyyyParse((a as TransactionModel).date)));
      filterTxns = txns;
    }
  }

  filterTxn(txn, keyword) {
    String txnLowerCase = txn.merchant.toLowerCase();
    String keywordLowerCase = keyword.toString().toLowerCase();
    return txnLowerCase.indexOf(keywordLowerCase) != -1;
  }

  @action
  Future filter(keyword) async {
    filterTxns = txns.where((txn) => filterTxn(txn, keyword)).toList();
  }

  @action
  Future filterByBudget(String budgetName) async {
    budgetTxns = txns.where((txn) => txn.budget == budgetName).toList();
  }
}

final TransactionStore txnStore = new TransactionStore();
